package cn.itrip.auth.controller;

import cn.itrip.auth.service.SmsService;
import cn.itrip.auth.service.TokenService;
import cn.itrip.auth.service.UserService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.beans.vo.userinfo.ItripUserVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.ErrorCode;
import cn.itrip.common.MD5;
import cn.itrip.common.RedisAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author yaozhaobao
 * @Date 2020/12/11 16:04
 * @Version 1.0
 **/
@RestController
@RequestMapping("/api")
public class UserController {

    Logger log = LoggerFactory.getLogger(UserController.class);


    @Resource
    UserService userService ;

    @Resource
    RedisAPI redisAPI;

    @Resource
    SmsService smsServcie;


    @Resource
    TokenService tokenService;



    @RequestMapping(value="registerbyphone",method = RequestMethod.POST)
    public Dto registerByPhone(@RequestBody ItripUserVO itripUserVO){

        //手机格式校验  11位数字（前端校验）
        //重复注册检查
        try {

            //是否存在userCode并且activated=1
            if(userService.checkUserByUserCode(itripUserVO.getUserCode())){
                //可以使用
                String code = MD5.getRandomCode()+"";
                //发送短信
                boolean rs=smsServcie.sendMessage(itripUserVO.getUserCode(),"圣乡堂","SMS_169900031","{'code':'"+code+"'}");
                if(rs){
                    try {
                        redisAPI.set("auth:" + itripUserVO.getUserCode(), 300, code);
                        try {
                            ItripUser itripUser = userService.getUserByUserCode(itripUserVO.getUserCode());
                            if (itripUser == null) {
                                //没有注册
                                itripUser=new ItripUser();
                                itripUser.setUserPassword(itripUserVO.getUserPassword());
                                itripUser.setUserName(itripUserVO.getUserName());
                                itripUser.setUserCode(itripUserVO.getUserCode());
                                itripUser.setCreationDate(new Date());
                                itripUser.setActivated(0);
                                if (userService.itripxAddUserByPhone(itripUser)) {
                                    return DtoUtil.returnSuccess("注册成功,请继续激活");
                                }
                                return DtoUtil.returnFail("插入数据失败，检查数据库", "100005");

                            } else {
                                //注册了，但是没有激活
                                return DtoUtil.returnFail("此用户之前已经注册请激活", "100004");
                            }
                        }catch (Exception e){
                            return DtoUtil.returnFail("数据库操作失败","100007");
                        }
                    }catch (Exception e){
                        return DtoUtil.returnFail("缓存数据失败，检查redis服务器","100003");
                    }
                }else{
                    return DtoUtil.returnFail("短信发送失败，无法注册","100001");
                }
            }else{
                //不能使用
                return DtoUtil.returnFail("用户名已经存在，并且已经激活成功了，不能使用该用户名","100002");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("注册失败","100006");
        }
    }

    @RequestMapping(value = "actived",method = RequestMethod.GET)
    public Dto inactived(String userCode,String code) {
        try{
            if(redisAPI.exist("auth:"+userCode)){
                if(redisAPI.get("auth:"+userCode).equals(code)){
                    //验证通过
                    ItripUser itripUser = null;
                    try {
                        itripUser = userService.getUserByUserCode(userCode);
                        itripUser.setActivated(1);

                        if(userService.itripxupdateUser(itripUser)){
                            return  DtoUtil.returnSuccess("激活成功");
                        }else{
                            return  DtoUtil.returnFail("数据库操作失败","100007");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        return  DtoUtil.returnFail("数据库操作失败","100007");
                    }
                }
            }
            return DtoUtil.returnFail("不存在此数据激活失败","100008");
        }catch (Exception e){
            return DtoUtil.returnFail("缓存数据失败，检查redis服务器","100003");
        }
    }


    @RequestMapping(value="/dologin",method = RequestMethod.POST)
    public Dto dologin(@RequestParam String userCode, @RequestParam String pwd, HttpServletRequest request){
        ItripUser itripUser;
        //1.数据库验证用户名和密码是否存在
        try {
           itripUser= userService.checkLogin(userCode,pwd);
           if(itripUser==null){
               return DtoUtil.returnFail("登录失败", ErrorCode.AUTH_AUTHENTICATION_FAILED);
           }
               //2.登录成功
            log.info("login:user-agent:"+request.getHeader("user-agent"));
            //3.生成token
            String token= tokenService.genarateToken(request.getHeader("user-agent"),itripUser);

            //4.放入到redis中设置过期时间、  key token  value userjson

            if(!tokenService.saveToken(token,itripUser)){
                return DtoUtil.returnFail("Redis异常",ErrorCode.AUTH_REDIS_ERROR);
            };
            //5.返回token到客户端 返回token，生成token时间 token过期时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = simpleDateFormat.parse(token.split("-")[3]);
            long gen= date.getTime();
            long expire=date.getTime()+TokenService.TOKEN_TIMEOUT;
            ItripTokenVO itripTokenVO = new ItripTokenVO(token,expire,gen);
            return DtoUtil.returnDataSuccess(itripTokenVO);
        } catch (Exception e) {
            e.printStackTrace();
            return  DtoUtil.returnFail("其他异常",ErrorCode.AUTH_UNKNOWN);
        }

    };


    /**
     * 注销功能
     * @param request
     * @return
     */
    @RequestMapping(value = "logout",method = RequestMethod.GET,produces="application/json")
    public Dto logout(HttpServletRequest request){

        //获取前端传过来的token 和agent
        String  token =request.getHeader("token");
        String agent=request.getHeader("user-agent");

        //获取前端的token  agent校验用户是否有效
        if(tokenService.validateToken(token,agent)){
            //执行退出,redis清楚token
            try {
                tokenService.deleteToken(token);
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail("redis异常",ErrorCode.AUTH_REDIS_ERROR);
            }
            return DtoUtil.returnSuccess("注销成功！");
        }

        return  DtoUtil.returnFail("token无效",ErrorCode.AUTH_TOKEN_INVALID);
    }


























}




